﻿using System;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using NUnit.Framework;

namespace WindsorInitConfig {
    [TestFixture]
    public class NamingConvention {
        [Test]
        public void tt() {
            var container = new WindsorContainer();
            container.RegisterSession("session-for-db1", c => c.CreateSessionFactoryForDb1());
            container.RegisterSession("session-for-db2", c => c.CreateSessionFactoryForDb2());
            var session = container.Resolve<ISession>("session-for-db1");
            Assert.AreEqual(1, session.Id);
        }
    }

    public interface ISessionFactory {
        ISession OpenSession();
    }

    public interface ISession {
        int Id { get; }
    }

    public class Session: ISession {
        public int Id { get; private set; }

        public Session(int id) {
            Id = id;
        }
    }

    public class SessionFactory : ISessionFactory {
        private readonly int id;

        public SessionFactory(int id) {
            this.id = id;
        }

        public ISession OpenSession() {
            return new Session(id);
        }
    }

    public class NHibernateConfigurator {
        public ISessionFactory CreateSessionFactoryForDb1() {
            return new SessionFactory(1);
        }

        public ISessionFactory CreateSessionFactoryForDb2() {
            return new SessionFactory(2);
        }
    }


    public static class WindsorSessionFactoryExtensions {
        public static void RegisterSession(this IWindsorContainer container, string name, Func<NHibernateConfigurator, ISessionFactory> configurator) {
            var id = Guid.NewGuid().ToString();
            container.Register(
                Component.For<ISessionFactory>()
                    .Named(id)
                    .LifeStyle.Singleton
                    .UsingFactoryMethod(() => configurator(new NHibernateConfigurator())),
                Component.For<ISession>()
                    .Named(name)
                    .LifeStyle.Transient // perwebrequest
                    .UsingFactoryMethod(k => k.Resolve<ISessionFactory>(id).OpenSession())
                );
        }
    }
}